articles

Home / DeveloperSection / Articles / Routing in Angular JS

Routing in Angular JS

Routing in Angular JS

Anubhav Kumar 145 19-May-2024

Routing in AngularJS is a core feature that allows you to build single-page applications (SPAs) by defining different views for different URLs. This is accomplished using the ngRoute module or the more advanced ui-router module. Below is a detailed explanation of how routing works in AngularJS and how you can implement it.

Basic Routing with ngRoute

Include the ngRoute module: First, make sure to include the angular-route.js script in your HTML file. This can be downloaded from the AngularJS website or included via a CDN.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>

Define the module dependency: Include ngRoute as a dependency in your AngularJS application module.

var app = angular.module('myApp', ['ngRoute']);

Configure the routes: Use the $routeProvider to define your routes and associate them with templates and controllers.

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
    .when('/home', {
        templateUrl: 'home.html',
        controller: 'HomeController'
    })
    .when('/about', {
        templateUrl: 'about.html',
        controller: 'AboutController'
    })
    .otherwise({
        redirectTo: '/home'
    });
}]);

Create the controllers: Define the controllers for each route.

app.controller('HomeController', ['$scope', function($scope) {
    $scope.message = 'Welcome to the Home Page!';
}]);

app.controller('AboutController', ['$scope', function($scope) {
    $scope.message = 'Learn more About Us!';
}]);

Set up the templates: Create the HTML templates for each route.

<!-- home.html -->
<h1>{{ message }}</h1>
<!-- about.html -->
<h1>{{ message }}</h1>

Link the routes in the main HTML file: Use ng-view to display the routed content.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS Routing Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <nav>
        <a href="#!/home">Home</a>
        <a href="#!/about">About</a>
    </nav>
    <div ng-view></div>
</body>
</html>

Thank You.


The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By